using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Zhaoxi.MSACommerce.Infrastructure._Common;
using ZhaoXi.MSACommerce.Infrastructure.EnityFrameworkCore;
using ZhaoXi.MSACommerce.Infrastructure.EnityFrameworkCore.interceptor;
using Zhaoxi.MSACommerce.PaymentService.Infrastructure.Data;

namespace Zhaoxi.MSACommerce.PaymentService.Infrastructure;

public static class DependencyInjection
{
    public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration configuration)
    {
        ConfigureEfCore(services, configuration);
            
        services.AddInfrastructureCommon();

        
        
        services.AddInfrastructurea(configuration); //先去掉服务发现
        
        ConfigureCap(services,configuration);
        
        return services;
    }

    private static void ConfigureEfCore(IServiceCollection services, IConfiguration configuration)
    {
        var dbConnection = configuration.GetConnectionString("DefaultConnection");

        services.AddDbContext<PaymentDbContext>((sp, options) =>
        {
            options.AddInterceptors(sp.GetRequiredService<AuditEntityInterceptor>());
            options.UseMySql(dbConnection, new MySqlServerVersion(new Version(8, 0, 0)));
        });
    }

    private static void ConfigureCap(IServiceCollection services, IConfiguration configuration)
    {
        var dbConn = configuration.GetConnectionString( name: "DefaultConnection");
        if (dbConn is null) throw new ArgumentNullException(nameof(dbConn));

        services.AddCap(x =>
        {
            x.UseEntityFramework<PaymentDbContext>();
            x.UseMySql(dbConn);
            x.UseRabbitMQ(options =>
            {
                configuration.GetSection("RabbitMQ").Bind(options);
            });
            x.UseDashboard();
        });
    }
}